<?php
namespace app\common\command;

use app\common\model\index\LoginModel;
use app\common\model\index\LoginTokenModel;
use phpseclib3\Net\SSH2;
use think\admin\Command;
use think\admin\service\ProcessService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;



/**
 * 例子
 *
 * @package app\store\command
 */
class LinuxCommand extends Command
{

    protected function configure()
    {
        $this->setName('linuxCommand')->setDescription('链接linux的工具服务');
        $this->addArgument('status', Argument::OPTIONAL, 'wokermen 状态命令' );
        $this->addArgument('other', Argument::OPTIONAL, 'wokermen 额外命令' );

    }
    /**
     * xml订单入表并推送报关
     * @param Input $input
     * @param Output $output
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {


        $user_arr = [];
        // 注意：这里与上个例子不同，使用的是websocket协议
        $ws_worker = new Worker("websocket://0.0.0.0:8082");

        // 启动4个进程对外提供服务
        $ws_worker->count = 4;

        $ws_worker->onConnect = function(TcpConnection $connection)
        {

        };

        // 当收到客户端发来的数据后返回hello $data给客户端
        $ws_worker->onMessage = function(TcpConnection $connection, $data) use (&$user_arr)
        {

            if (strpos($data, 'UserId') !== false) { // 获得用户id 根据用户id检测目录

                $user_id = substr($data,7, strlen($data)-1);
                $path    = public_path("ssh").$user_id;
          
                // 检查目录是否存在
                if ( !file_exists( $path ) && !mkdir($path, 0755, true)) {

                    $result = ['prompt' => 'root@IP_ADDRESS:#', 'data' => ['无法识别用户目录'], 'status' => 'error'];
                    $connection->send(json_encode($result));
                }

                $user_arr[$connection->id] = "cd public/ssh/{$user_id} && ";
                
            }

            if ( !isset($user_arr[$connection->id]) ){
                $result = ['prompt' => 'root@IP_ADDRESS:#', 'data' => ['请先登陆'], 'status' => 'error'];
                $connection->send(json_encode($result));
            }

            // 判断 是否

            $data = ProcessService::exec($user_arr[$connection->id]. $data, true);

            $result = ['prompt' => 'root@IP_ADDRESS:#', 'data' => $data, 'status' => 'good'];
            $connection->send(json_encode($result));
        };

        // 运行worker
        Worker::runAll();
    }



    public function login ()
    {
        return 1;
        $ssh = new SSH2('8.135.41.209');
        if (!$ssh->login('root', '(Awrsyywn5241151)')) {
            exit('登录失败');
        }

        return $ssh;
    }
}

?>